package com.neu.common.utils;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * Yao
 */
public class ListCloneUtil {
    public static <T> List<T> clone(List<T> list, Class<T> tClass) throws Exception {
        if (list == null) return new ArrayList<>();
        Class[] interfaces = tClass.getInterfaces();
        int flag = 0;
        for(Class classItem : interfaces){
            if(classItem == Cloneable.class){
                flag = 1;
                break;
            }
        }
        if(flag == 0){
            throw new Exception("当前容器的元素为实现Cloneable接口");
        }
        ArrayList<T> result = new ArrayList<>();
        for(T t : list){
            Method cloneMethod = tClass.getMethod("clone",null);
            T newOne = (T) cloneMethod.invoke(t);
            result.add(newOne);
        }
        return result;
    }
}
